footerfun()
hotkeyfn()
userCenter()



const eid = window.sessionStorage.getItem('goodsId')
if (!eid) window.location.href = "../views/index2.html"
bindHTML()

// others()
sortHandler()


function bindHTML() {
    pAjax({
        url: 'https://www.lemall.com/api/cate/secondlist.html',
        data: {
            visitPath: `${eid}-1-0`
        },
        dataType: 'json'
    }).then(res => {
        const leftBox = document.querySelector(".list-show-left>dl")
        let str = `<dt><span>${res.data.productCate.name}</span></dt>`;
        res.data.childCates.forEach(item => {
            // console.log(item.id);
            str += `
            <dd data-did="${item.id}">${item.name}</dd>
            `
        })
        leftBox.innerHTML = str;

        let show = ``;
        const mainBox = document.querySelector('.main-item')
        res.data.productList.forEach(item => {
            show += `
            <li data-did='${item.id}'>
            <img src="${item.masterImg}" alt="">
            <h2>${item.name1}</h2>
            <h3>￥${item.mallPcPrice} <del style="font-size:13px;color:#999;">¥${item.marketPrice}</del><i style="font-size:12px; font-style:normal;float:right">${item.commentsNumber}条评论</i></h3>
            <p>
                <a  data-did='${item.id}' class="toDetail">查看详情</a>
                <a  data-did='${item.id}' class="addCart">加入购物车</a>
            </p>
       </li>
       &
            `
        })

        // mainBox.innerHTML=show;

        mainBox.addEventListener('click', e => {
            if (e.target.className === 'toDetail') {
                window.sessionStorage.setItem('goodsId', e.target.dataset.did)

                window.open("../views/detail.html")

            }
            if (e.target.className === 'addCart') {
                const goodsId = e.target.dataset.did - 0
                window.sessionStorage.setItem('goodsId', goodsId )
                
                addCart(goodsId)
               

            }
        })
        pagerHandler(show, mainBox)



    })

}



function pagerHandler(str, box) {
    // 先把数据扩充
    for (let i = 0; i < 5; i++) {
        str += str
    }
    str = str.split("&")
    // 点击下一页
    let current = 8;
    let pageCount = ~~(str.length / current)
    let count = 1;
    const pagerBox = document.querySelector(".pager")
    let ss = `
    <a class="first">首页</a>
    <ul class="select">
        <li data-num =" ${current}">${current}</li>
        <li data-num="4">4</li>
        <li data-num="8">8</li>
        <li data-num="12">12</li>
        <li data-num="16">16</li>
    </ul>
    <a class="sup">-</a>
    <span>${count}</span>    
    <a class="add">+</a>
    <a class="last">尾页</a>
    <i>共${pageCount}页</i>
    `
    pagerBox.innerHTML = ss
    let a = (count - 1) * current;
    let b = count * current
    str1 = str.slice(a, b)
    str1 = str1.join('')
    box.innerHTML = str1;


    //分页事件

    pagerBox.addEventListener('click', e => {
        if (e.target.className === "first") {
            count = 1
        }
        if (e.target.className === "last") {
            count = pageCount
        }
        if (e.target.className === "add") {
            count >= pageCount ? pageCount : count++
        }
        if (e.target.className === "sup") {
            count <= 1 ? 1 : count--
        }
        if (e.target.nodeName === "LI") {
            current = e.target.dataset.num
            pageCount = ~~(str.length / current)
        }
        ss = `
        <a class="first">首页</a>
        <ul class="select">
            <li data-num =" ${current}">${current}</li>
            <li data-num="4">4</li>
            <li data-num="8">8</li>
            <li data-num="12">12</li>
            <li data-num="16">16</li>
        </ul>
        <a class="sup">-</a>
        <span>${count}</span>       
        <a class="add">+</a>
        <a class="last">尾页</a>
        <i>共${pageCount}页</i>
        `
        a = (count - 1) * current;
        b = count * current
        pagerBox.innerHTML = ss
        str1 = str.slice(a, b)
        str1 = str1.join('')
        box.innerHTML = str1;
    })
}
// sortHandler()

function sortHandler() {
    const sortBox = document.querySelector(".sort")
    console.log(sortBox);
    sortBox.addEventListener("click", e => {
        console.log(11);
        [...sortBox.children].forEach(item => {
            item.classList.remove('active')
            e.target.classList.add('active')
        })
        let sortId = e.target.dataset.sort;

        pAjax({
            url: 'https://www.lemall.com/api/cate/secondlist.html',
            data: {
                visitPath: `${eid}-1-${sortId}`
            },
            dataType: 'json'
        }).then(res => {
            let show = ``;
            const mainBox = document.querySelector('.main-item')
            res.data.productList.forEach(item => {
                show += `
                <li data-did='${item.id}'>
                <img src="${item.masterImg}" alt="">
                <h2>${item.name1}</h2>
                <h3>￥${item.mallPcPrice} <del style="font-size:13px;color:#999;">¥${item.marketPrice}</del><i style="font-size:12px; font-style:normal;float:right">${item.commentsNumber}条评论</i></h3>
                <p>
                    <a  data-did='${item.id}' class="toDetail">查看详情</a>
                    <a  data-did='${item.id}' class="addCart">加入购物车</a>
                </p>
           </li>
            &
            `;
                pagerHandler(show, mainBox)

            })
        })

    })
}


// --------




function others() {
    const logoBox = document.querySelector('.logo')
    logoBox.addEventListener('click', () => {
        window.location.href = "./index.html"
    })
}


async function addCart(goodsId) {
    // 1. 拿到 localStroage 内的 id 和 token
    const id = window.localStorage.getItem('id')
    const token = window.localStorage.getItem('token')
    //   console.log(id);
    // 2. 验证 id 是否存在
    if (!id) {
        const res = window.confirm('您还没有登录, 请登录后在购买, 点击确定跳转回登录页, 点击取消留在当前页面')
        if (res) {
            window.location.href = '../views/login.html'
            return
        }
        return
    }

    const res = await pAjax({
        url: 'http://localhost:8888/cart/add',
        method: 'POST',
        data: {
            id,
            goodsId
        },
        headers: {
            authorization: token
        },
        dataType: 'json'
    })
    //   console.log(res);
    if (res.code === 401) {
        const res = window.confirm('您的登录已经过期, 请重新登录后在购买, 点击确定跳转回登录页, 点击取消留在当前页面')
        if (res) {
            window.location.href = './login.html'
            return
        }
        return
    }

    if (res.code === 1) {
        alert('加入购物车成功')
    }
}


var goTop = document.querySelector('.goTop')
goTop.onclick = function () {

window.scrollTo({ top: 0, behavior: 'smooth' })
}



$(window).scroll(()=>{
    // 拿到浏览器卷去的高度
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
    
        if(scrollTop < 450){
            $('.goTop').addClass('a').removeClass('b')
        }else{
            $('.goTop').removeClass('a').addClass('b')
        }
    
})